﻿/*
创建人：Wangjh
日期：2022-04-28
描述：有限排产js
*/
var page = {
  oldSeq: null,
  pagetotal: 0,
  pageSize: 20,//一个排产池的记录一起生成优先级策略，目的是不分页yuxj20230220
  pageNumber: 1,
  rootPath: getRootPath(), //网站根路径
  ajaxUrl: getRootPath() + "/Ashx/ApsHandler/ApsLimitedCapacityHandler.ashx",
  //初始化页面
  init: function () {
    page.bind();
    NewcustomizedEasyuiPagination('pp'); //定制化分页
    $('#pp').find('.pageSize').val(page.pageSize); //初始化行数
    page.addEditCell();
  },
  addEditCell: function () //给easyuigrid新增editcell方法
  {
    $.extend($.fn.datagrid.methods, {
      editCell: function (jq, param) {
        return jq.each(function () {
          var opts = $(this).datagrid('options');
          var fields = $(this).datagrid('getColumnFields', true).concat($(this).datagrid('getColumnFields'));
          for (var i = 0; i < fields.length; i++) {
            var col = $(this).datagrid('getColumnOption', fields[i]);
            col.editor1 = col.editor;
            if (fields[i] != param.field) {
              col.editor = null;
            }
          }
          $(this).datagrid('beginEdit', param.index);
          for (var i = 0; i < fields.length; i++) {
            var col = $(this).datagrid('getColumnOption', fields[i]);
            col.editor = col.editor1;
          }
        });
      }
    });
  },
  endEditing: function (gridId) {
    if (page.editIndex == undefined) { return true }
    if ($('#' + gridId).datagrid('validateRow', page.editIndex)) {
      $('#' + gridId).datagrid('endEdit', page.editIndex);
      page.editIndex = undefined;
      return true;
    } else {
      return false;
    }
  },
  //页面事件绑定
  bind: function () {
    $('#PoolID').combobox({
      valueField: 'APSPOOLID',
      textField: 'APSPOOLNAME',
      onSelect: function (record) {
        page.isScheduledApsPool(record.APSPOOLID);
      },
      onLoadSuccess: function () {
        var data = $('#PoolID').combobox('getData');
        if (data.length > 0) {
          $('#PoolID').combobox('select', data[0].APSPOOLID);
        }
      }
    });
    //排产池列表
    $("#gdApsPool").datagrid({
      onLoadSuccess: function (data) {
        $('#pp').pagination('refresh', {	// 改变选项，并刷新分页栏信息
          total: page.pagetotal,
          pageSize: page.pageSize,
          pageNumber: parseInt(page.pageNumber)
        });
        NewcustomizedEasyuiPagination('pp'); //定制化分页
        //提示消息样式
        $("#dvApsPool .tip").addClass('icon-standard-exclamation');
        //console.log(data);
      },
      onCheck: function (index, rowData) {
        page.reset(false, false, true);
        page.searchContainerAps();
        //console.log('onCheck');
      },
      onUncheck: function (index, rowData) {
        page.reset(false, false, true);
        page.searchContainerAps();
        //console.log('onUncheck');
      },
      onCheckAll: function (index, rowData) {
        page.reset(false, false, true);
        page.searchContainerAps();
        //console.log('onCheckAll');
      },
      onUncheckAll: function (index, rowData) {
        page.reset(false, false, true);
        page.searchContainerAps();
        //console.log('onUncheckAll');
      },
      onClickCell: function (index, field) {
        //编辑单元格
        if (page.endEditing('gdApsPool')) {
          $('#gdApsPool').datagrid('editCell', { index: index, field: field });
          page.editIndex = index;
        }
        //var e=arguments.callee.caller.caller.arguments[0]; 
        //console.log('onClickCell'); 
        return false;
      },
      columns: [[
        { field: 'ck', title: '选择', checkbox: true },
        { field: 'MFGORDERNAME', title: '订单号', width: 120 },
        { field: 'WORKCENTERNAME', title: '中心', width: 100 },
        { field: 'TEAMNAME', title: '件号主制单元', width: 100 },
        { field: 'PRIORITYCODENAME', title: '订单优先级', width: 80 },
        { field: 'CONTAINERNAME', title: '批次', width: 180 },
        { field: 'PRODUCTDESC', title: '零件名称', width: 130 },
        { field: 'QTY', title: '在制数', width: 60 },
        { field: 'ISPREPARE', title: '齐套', width: 60 },
        { field: 'STEPDURATION', title: '批次总期量', width: 80 },
        { field: 'CRITICALVALUE', title: '批次临界比', width: 80 },
        { field: 'APSSEQUENCE', title: '排产顺序号', width: 80, editor: { type: 'numberbox' } },
        {
          field: 'WORKFLOWINFO', title: '工艺信息', width: 180, formatter: function (value, row, index) {
            var url = "forms/Custom/htmlPage/WorkCenterMaintainPage.html?type=1,3,4" +
              "&pname=" + row.PRODUCTNAME + "&pid=" + row.PRODUCTID + "&wname=" + row.WORKFLOWNAME + "&wid=" + row.WORKFLOWID;//encodeURI(
            //return '<a target="_blank" href='+url+' style=""  >'+value+'</a>';
            return '<a target="_blank" onclick="top.mainWorkPage.addTab(\'APS-工序生产周期维护\',\'' + url + '\',true);return false;" href="#" style=""  >' + value + '</a>';
          }
        },
        { field: 'WORKFLOWSTEPNAME', title: '当前工序', width: 180 },
        { field: 'CONTAINERTYPENAME', title: '流水卡类型', width: 100 },
        {
          field: 'REALSTARTDATE', title: '实际开始日期', width: 105, formatter: function (value, row, index) {
            if (value != null)
              return dayjs(value).format("YYYY-MM-DD");
          }
        },
        {
          field: 'REALSTARTDATE2', title: '手动指定开始', width: 105, editor: { type: 'datebox' }, formatter: function (value, row, index) {
            if (value != null) {
              return dayjs(value).format("YYYY-MM-DD");
            }
            if (row.EXPECTMATERIALDATE != null) {
              row.REALSTARTDATE2 = row.EXPECTMATERIALDATE;
              return dayjs(row.EXPECTMATERIALDATE).format("YYYY-MM-DD");
            }
          }
        },
        { field: 'MFGSTARTDATE', title: '订单开始日期', width: 105 },
        { field: 'MFGENDDDATE', title: '订单结束日期', width: 105 },
        {
          field: 'ISSUBCON', title: '主子卡', width: 70, formatter: function (value, row, index) {
            return value == "1" ? "子卡" : "主卡";

          }
        },
        {
          field: 'LOGMESSAGE', title: '排产日志', width: 80, formatter: function (value, row, index) {
            if (value != null) {
              return '<div class="tip" title=' + value.replace(/[ ]|[\r\n]/g, "") + ' style="height:20px;color:red;cursor: pointer;" >' + '' + '</div>';
              //return '<div data-options="position:\'left\'" class="easyui-tooltip" title="'+value.replace(/[\r\n]/g, "")+'请按照网上希尔顿吃软饭是通过不优化怒江面孔aqzwsxedcrfvtgbyhnujmikolpoiuyhgtrfdewsqazxcvbnmjklioop" style="color:red;width:100px;padding:5px">'+'. . .'+'</div>';
            }
          }
        },
        { field: 'APSPOOLID', title: 'APSPOOLID', hidden: true },
        { field: 'CONTAINERID', title: 'CONTAINERID', hidden: true },
        { field: 'WORKFLOWID', title: '工艺', hidden: true },
        { field: 'TOGETHERFLAG', title: '批次顺序', hidden: true },
        { field: 'CONTAINERTYPE', title: '流水卡类型', hidden: true },
        { field: 'PRODUCTID', title: '零件图号ID', hidden: true },
        { field: 'PRODUCTNAME', title: '零件图号', hidden: true },
        { field: 'PRODUCTREVISION', title: 'PRODUCTREVISION', hidden: true },
        { field: 'WORKFLOWNAME', title: 'WORKFLOWNAME', hidden: true },
        { field: 'WORKFLOWREVISION', title: 'WORKFLOWREVISION', hidden: true }

      ]],
      onBeforeEdit: function (rowIndex, rowData) {
        page.oldSeq = rowData.APSSEQUENCE
      },
      onAfterEdit: function (index, row, change) {
        if (change.APSSEQUENCE != null && page.oldSeq != row.APSSEQUENCE)//更改的顺序号
        {
          page.saveSingleSequence(row["CONTAINERID"].toString(), row.APSSEQUENCE, row["APSPOOLID"].toString());
          page.oldSeq = null;
        }
        if (change.REALSTARTDATE2 != null)//更改的手动开始日期
        {
          page.saveManualStartDate(row);
        }
        //提示消息样式
        $("#dvApsPool .tip").addClass('icon-standard-exclamation');
      }
    });
    //分页事件
    $('#pp').pagination({
      onSelectPage: function (pageNumber, pageSize) {
        NewcustomizedEasyuiPagination('pp'); //定制化分页
        page.pageSize = pageSize; page.pageNumber = pageNumber;
        page.searchData();
      }
    });
    //绑定分页go按钮
    $('#pageGo').on("click", function () {
      var pageNumber = $(this).parents('tr').find('.pagination-num').val();
      page.pageNumber = pageNumber;
      page.pageSize = $('#pp').find('.pageSize').val() == "" ? page.pageSize : Number($('#pp').find('.pageSize').val());
      page.searchData();
    });
    //批次排产信息
    $("#gdContainerAps").datagrid({
      groupField: 'CONTAINERNAME',
      view: groupview,
      groupFormatter: function (value, rows) {
        var val = value + ' - ' + '已排 ' + rows.length + ' 种策略'
        return val; //"<span data-count=" + rows.length + " class='customTitle' >" + val + "</span>";
      },
      columns: [[
        //                 { field: 'ck', title: '选择', checkbox: true },
        { field: 'MFGORDERNAME', title: '订单号', width: 120 },
        { field: 'CONTAINERNAME', title: '批次', width: 150 },
        { field: 'PRODUCTDESC', title: '零件名称', width: 130, hidden: true },
        { field: 'QTY', title: '在制数', width: 60 },
        { field: 'WORKFLOWINFO', title: '工艺信息', width: 180, hidden: true },
        {
          field: 'STARTTIME', title: '开始时间', width: 125, formatter: function (value, row, index) {
            if (value != null)
              return value.substring(0, value.lastIndexOf(":"));
          },
          styler: function (value, row, index) {
            if (value != null && dayjs(dayjs(value).format('YYYY-MM-DD')) < dayjs(dayjs(row.MFGSTARTDATE).format('YYYY-MM-DD'))) {//REALSTARTDATE
              row.isOverdue = "1";//1开始时间超期，2结束时间超期
              return 'background-color:#ffee00;';
            }
          }
        },
        {
          field: 'ENDTIME', title: '结束时间', width: 125, formatter: function (value, row, index) {
            if (value != null)
              return value.substring(0, value.lastIndexOf(":"));
          },
          styler: function (value, row, index) {
            if (value != null && dayjs(dayjs(value).format('YYYY-MM-DD')) > dayjs(dayjs(row.MFGENDDDATE).format('YYYY-MM-DD'))) {
              row.isOverdue = "2";//1开始时间超期，2结束时间超期
              return 'background-color:#ffee00;';
            }
          }
        },
        {
          field: 'APSTYPE', title: '排产策略', width: 80, formatter: function (value, row, index) {
            switch (value) {
              case "1":
                return "正排";
                break;
              case "2":
                return "倒排";
                break;
              case "3":
                return "瓶颈排";
                break;
              default:
                return "";
                break;
            }
          }
        },
        {
          field: 'OPERATE', title: '操作', width: 230, formatter: function (value, row, index) {
            var para = {
              CONTAINERID: row.CONTAINERID,
              WORKFLOWID: row.WORKFLOWID,
              APSPLANINFOID: row.APSPLANINFOID
            }

            var btnHtml = "<button   class='' onclick=page.viewGanttAndSave('" + JSON.stringify(para) + "',false) style='cursor:pointer;width: 40px; height: 22px'>查看</button>";
            btnHtml += "<button title='查看此批次有限排产的3种策略对比甘特图'  class='' onclick=page.viewGanttAndSave('" + JSON.stringify(para) + "',true) style='cursor:pointer;margin-left:10px;width: 80px; height: 22px'>策略对比</button>";


            btnHtml += "<button title=''  class='' onclick=page.overDueAnalysis('" + JSON.stringify({
              CONTAINERID: row.CONTAINERID,
              isOverdue: row.isOverdue,
              APSTYPE: row.APSTYPE
            }) + "') style='display:none;cursor:pointer;margin-left:10px;width: 80px; height: 22px'>超期建议</button>";
            btnHtml += "<button class=''  onclick=page.deleApsPlanInfo('" + row.APSPLANINFOID + "') style='margin-left:10px;cursor:pointer;width: 40px; height: 22px'>删除</button>";//新增删除功能，add by zhangrj 20231130
            return btnHtml
          }
        },
        { field: 'WORKFLOWID', title: '工艺', hidden: true },
        { field: 'CONTAINERID', title: 'CONTAINERID', hidden: true }

      ]]
    });

    //清除按钮
    $('#btnReset').on("click", function () {
      page.reset(true, true, true);
      page.pageNumber = 1; page.pagetotal = 0
      $('#pp').pagination('refresh', {
        total: page.pagetotal,
        pageSize: page.pageSize,
        pageNumber: page.pageNumber
      });
    });
    //移入批次按钮
    $('#btnAddPool').on("click", function () {
      page.addApsPool();
    });
    //移出批次按钮
    $('#btnRemoveApsPool').on("click", function () {
      page.removeApsPool();
    });
    //查询按钮
    $('#btnSearch').on("click", function () {
      page.reset(false, true, true);
      page.pageNumber = 1;
      var strPoolId = $("#PoolID").combobox('getValue');
      if (strPoolId == "") {
        displayMessage("没有排产池", false);
        return;
      }

      page.searchData();
    });
    //查询按钮，绑定回车事件
    $(document).keypress(function (event) {
      if (event.which === 13) {
        //点击回车要执行的事件
        $('#btnSearch').click();
      }
    });

    //排产期量计算及排产优先级计算
    $('#btnCalcStepDuration').on("click", function () {
      page.calcContainerApsPriority();
    });

    //排产计算
    $('#btnLMAps').on("click", function () {
      page.apsLmCalculate();
    });
    //排产结果导出
    $('#btnLMApsExport').on("click", function () {
      clearMessage();
      page.apsLmCalculateExport();
    });
    //错误日志导出
    $('#btnTaskLogsExport').on("click", function () {
      clearMessage();
      page.apsContainerScheduledTaskLogsExport();
    });
    //排产结果导入错误列表
    $("#ErrorTable").datagrid({
      columns: [[
        { field: 'apsplandetailid', hidden: true },
        { field: 'productname', title: '件号', width: '100px' },
        { field: 'workflowstepname', title: '工序', width: '160px' },
        { field: 'Error', title: '出错原因', width: '400px' }
      ]]
    });
    //保存手动排产开始日期
    $('#btnManual').on("click", function () {
      page.saveManualStartDate();
    });
    //排产池导出
    $('#btnApsPoolExport').on("click", function () {
      var strPoolId = $("#PoolID").combobox('getValue');
      if (strPoolId == "") {
        displayMessage("没有排产池", false);
        return;
      }
      page.apsPoolExport();
    });
    //倒排指定结束日期 add:wangjh 20250702
    $('#btnRevAndManualAps').on("click", function () {
        page.openEndDateDialog();
    });
    //倒排指定日期窗口取消
    $('#dgMEDCancel').on("click", function () {
        clearMessage();
        $('#dgManualEndDate').dialog('close');
    });
    //倒排指定日期窗口确定
    $('#dgMEDSave').on("click", function () {
         clearMessage();
         page.apsLmReverseAndManualCalculate();
    });

    page.apsUploader();
    page.loadFactory();
    apsSeq.bind();
  },
  //倒排指定日期-计算 add:wangjh 20250702
  apsLmReverseAndManualCalculate:async function(){
    $("#dgMEDSave").linkbutton('disable');
    var endDate=$("#dgMEDEndDate").datebox("getValue");
    var selectData=$("#dgManualEndDate").dialog('options').popupData;
    if(selectData==null){
        displayMessage2("未选中批次", false, ["dgMEDSave"]);
        return;
    }
    if(isNullOrWhiteSpaceStr(endDate)){
         displayMessage2("请选择日期", false, ["dgMEDSave"]);
        return;
    }
    var containers = selectData.map(function (item) {
      return {
        apspoolid: item.APSPOOLID,
        ISSUBCON: item.ISSUBCON,
        containerid: item.CONTAINERID,
        containername: item.CONTAINERNAME,
        workflowid: item.WORKFLOWID,
        STARTTIME: isNullOrWhiteSpaceStr(item.REALSTARTDATE2) ? item.REALSTARTDATE : item.REALSTARTDATE2,
        ENDTIME: endDate,
        CONTAINERTYPE: item.CONTAINERTYPE,
        TOGETHERFLAG: item.TOGETHERFLAG,
        BEGINSEQUENCE: item.BEGINSEQUENCE,
        DJDKSPECIAL: 2//单件单卡特殊处理，1：所有时间乘以大批数量,2：加工时间乘以大批数量 
      }
    });
    //console.log(selectData);
    var postData = {
      action: "apsLmCalculate",
      apstype: "2",
      isWholePool: 0,
      containers: JSON.stringify(containers)
    }
    console.log('指定结束日期计算请求',postData);
    //return;
    $.ajax({
      type: "Post",
      url: page.ajaxUrl,
      data: postData,
      cashe: false,
      async: true,
      beforeSend: function () {
        $.messager.progress({ text: '', msg: '处理中...' });
      },
      success: function (data) {
        //console.log(data);
        $.messager.progress('close');
        var result = JSON.parse(data);
        if (result.Result) {
          var dt = result.DBTable;
          $("#gdContainerAps").datagrid('loadData', { total: dt.length, rows: dt });
          displayMessage("排产成功,错误信息请看排产日志", true);
        } else {
          displayMessage(result.Message, false);
        }
        $("#dgMEDSave").linkbutton('enable');
        $('#dgManualEndDate').dialog('close');
      },
      error: function (XMLHttpRequest, textStatus, errorThrown) {
        $("#dgMEDSave").linkbutton('enable');
        $.messager.progress('close');
        alert(XMLHttpRequest.responseText);
      }
    });
  },
  //倒排指定日期-打开窗口 add:wangjh 20250702 
  openEndDateDialog: function(){ 
    var apstype = '2';

    //判断查询列表中是否有值
    var pageData = $("#gdApsPool").datagrid("getRows");
    if (pageData.length == 0) {
      displayMessage2("没有需要排产的数据", false, ["btnRevAndManualAps"]);
      return;
    }

    //如有勾选时，按照勾选的记录处理  
    var selectData = $("#gdApsPool").datagrid('getChecked');
    var strPoolId = $("#PoolID").combobox('getValue');
    //没有排产池且没有勾选数据时提示
    if (strPoolId == "" && selectData.length == 0) {
      displayMessage2("请选择需要排产的数据", false, ["btnRevAndManualAps"]);
      return;
    }
    if(selectData.length!=1){
      displayMessage2("请选择单条数据", false, ["btnRevAndManualAps"]);
      return;
    }

    var top = $("#btnRevAndManualAps").offset().top -300; 

    $('#dgManualEndDate').dialog({
            title: '手动指定结束日期',
            fit: false,
            top:top,
            width: 300,
            height: 130,
            closed: false,
            cache: false,
            modal: true,
            returnData: null,
            popupData: selectData, 
            onClose: function () {
                var re = $("#dgManualEndDate").dialog('options').returnData;
                $('#dgMEDEndDate').datebox('clear');
            }
        });


  },
  //排产池数据导出
  apsPoolExport: function () {
    var param = {
      action: "ExportApsPoolDataToExcel",
      pageSize: page.pageSize,
      pageNumber: page.pageNumber,
      containerName: $("#txtContainer").textbox('getValue'),
      mfgorderName: $("#txtMfgorderName").textbox('getValue'),
      productName: $("#txtProduct").textbox('getValue'),
      factoryId: $("#factoryID").combobox('getValue'),
      poolId: $("#PoolID").combobox('getValue'),//排产池yuxj20230218
      orderBStartDate: $("#txtOrderBStartDate").datebox('getValue'),
      orderEStartDate: $("#txtOrderEStartDate").datebox('getValue'),
      orderBEndDate: $("#txtOrderBEndDate").datebox('getValue'),
      orderEEndDate: $("#txtOrderEEndDate").datebox('getValue'),
      realBStartDate2: $("#txtRealSStartDate2").datebox('getValue'),//手动指定日期范围           
      realEStartDate2: $("#txtRealEStartDate2").datebox('getValue'),
      workflowStepName: $("#txtStepName").textbox('getValue'),
      isPrepare: $("#ddlIsPrepare").combobox('getValue'),
      isAps: $('#IsAps').combobox('getValue'),
      workcenterid: $("#workcenterid").textbox('getValue'),
      teamid: $("#teamid").textbox('getValue')
    };
    if (!isNullOrWhiteSpaceStr(param.orderBStartDate) && !isNullOrWhiteSpaceStr(param.orderEStartDate)) {
      if (dayjs(param.orderEStartDate) < dayjs(param.orderBStartDate)) {
        displayMessage("开始时间不能大于结束时间", false);
        return;
      }
    }
    if (!isNullOrWhiteSpaceStr(param.orderBEndDate) && !isNullOrWhiteSpaceStr(param.orderEEndDate)) {
      if (dayjs(param.orderEEndDate) < dayjs(param.orderBEndDate)) {
        displayMessage("开始时间不能大于结束时间", false);
        return;
      }
    }
    //导出文件
    FileDownLoad(page.ajaxUrl, param);
  },
  //分厂下拉初始化
  loadFactory: function () {
    $.ajax({
      type: "Post",
      url: getRootPath() + "/Ashx/CommonHandler.ashx?action=getFactory",
      data: {},
      cashe: false,
      async: true,
      beforeSend: function () {
      },
      success: function (data) {
        var result = JSON.parse(data);
        $('#factoryID').combobox({
          data: result,
          valueField: 'FACTORYID',
          textField: 'FACTORYNAME',
          value: result[0].FACTORYID, //默认值   
          onSelect: function (record) {
            if (record.FACTORYID !== "") {
              $('#PoolID').combobox('clear');
              page.loadPool(record.FACTORYID); //加载排产池
              page.getWorkcenter(record.FACTORYID);
              $('#teamid').textbox('clear');
            }
          }
        });
      },
      error: function (XMLHttpRequest, textStatus, errorThrown) {
      }
    });
  },
  //查询工区
  getWorkcenter: function (factoryid) {
    var mainUrl = getRootPath() + "/Ashx/ProductTeamInfoMaintPageHandler.ashx";//本页面后台路径
    $.ajax({
      type: "post",
      url: mainUrl + "?actions=getWorkcenter",
      data: { action: "getWorkcenter", factoryid: factoryid },
      cashe: false,
      dataType: 'json',
      success: function (res) {
        if (res.Result) {
          $("#workcenterid").combobox({
            valueField: 'workcenterid',
            textField: 'workcentername',
            panelHeight: 200,
            data: res.DBTable,
            onSelect: function (record) {
              if (record.workcenterid) {
                page.getTeam(record.workcenterid);
              }
            }
          });
        }
      }
    });
  },
  // 查询单元
  getTeam: function (workcenterid) {
    var mainUrl = getRootPath() + "/Ashx/ProductTeamInfoMaintPageHandler.ashx";//本页面后台路径
    $.ajax({
      type: "post",
      url: mainUrl + "?actions=getTeam",
      data: { action: "getTeam", workcenterid: workcenterid },
      cashe: false,
      dataType: 'json',
      success: function (res) {
        if (res.Result) {
          $("#teamid").combobox({
            valueField: 'teamid',
            textField: 'teamname',
            panelHeight: 200,
            data: res.DBTable
          });
        }
      }
    });
  },
  //排产池是否正在被定时任务计算
  isScheduledApsPool: function (apspoolid) {
    $.ajax({
      type: "Post",
      url: page.ajaxUrl,
      data: { action: "isScheduledApsPool", apspoolid: apspoolid },
      cashe: false,
      async: true,
      beforeSend: function () {
      },
      success: function (data) {
        var result = JSON.parse(data);
        if (result.Result) {

          //displayMessage("此排产池正在定时任务计算中，请稍后操作",true);

          $.messager.show({
            style: {
              top: 10
            },
            title: '警告！',
            msg: '此排产池正在定时任务计算中，请稍后操作',
            timeout: 0,
            showType: 'fade'
          });

          //禁用查询
          $("#btnSearch").linkbutton('disable');
        } else {
          //释放查询
          $("#btnSearch").linkbutton('enable');
        }
      },
      error: function (XMLHttpRequest, textStatus, errorThrown) {
      }
    });
  },
  //排产池列表初始化
  loadPool: function (factoryId) {
    $.ajax({
      type: "Post",
      url: page.ajaxUrl,
      data: { action: "getPoolList", factoryId: factoryId },
      cashe: false,
      async: true,
      beforeSend: function () {
      },
      success: function (data) {
        var result = JSON.parse(data);
        $('#PoolID').combobox('loadData', result);
      },
      error: function (XMLHttpRequest, textStatus, errorThrown) {
      }
    });
  },
  //保存调整的顺序号
  saveSingleSequence: function (containerid, apsSeq, apsPoolid) {
    $.ajax({
      type: "Post",
      url: page.ajaxUrl,
      data: { action: "saveSingleSequence", containerID: containerid, seq: apsSeq, poolid: apsPoolid },
      cashe: false,
      async: true,
      beforeSend: function () {
      },
      success: function (data) {
        var result = JSON.parse(data);
        if (result.Result) {
          page.searchData();
          displayMessage("保存成功", true);
        } else {
          page.searchData();
          displayMessage(result.Message, false);
        }
      },
      error: function (XMLHttpRequest, textStatus, errorThrown) {
      }
    });
  },
  //保存手动指定的开始日期
  saveManualStartDate: function (row) {
    clearMessage();
    $('#gdApsPool').datagrid('acceptChanges');
    //        var selectData = $("#gdApsPool").datagrid('getChecked');
    //        if ( selectData.length==0)
    //        {
    //            displayMessage("请选择需要排产的数据", false);
    //            return;
    //        }

    var selectData = [];
    selectData.push(row);

    var containers = selectData.map(function (item) {
      return {
        containerid: item.CONTAINERID,
        REALSTARTDATE2: item.REALSTARTDATE2
      }
    });
    var postData = {
      action: "saveManualStartDate",
      containers: JSON.stringify(containers)
    }
    $.ajax({
      type: "Post",
      url: page.ajaxUrl,
      data: postData,
      cashe: false,
      async: true,
      beforeSend: function () {
        $('#gdApsPool').datagrid('loading');
        //$.messager.progress({ text: '', msg: '处理中...' });
      },
      success: function (data) {
        $('#gdApsPool').datagrid('loaded');
        //$.messager.progress('close');
        var result = JSON.parse(data);
        if (result.Result) {
          page.searchData();
          displayMessage(result.Message, true);
        } else {
          displayMessage(result.Message, false);
        }
      },
      error: function (XMLHttpRequest, textStatus, errorThrown) {
        $('#gdApsPool').datagrid('loaded');
        // $.messager.progress('close');
        alert(XMLHttpRequest.responseText);
      }
    });

  },
  //结果导出
  apsLmCalculateExport: function () {
    var apstype = $('#apsType :checked').val();
    if (apstype == null) {
      displayMessage("请先选择排产策略", false);
      return;
    }
    var selectData = $("#gdApsPool").datagrid('getChecked');
    if (selectData.length == 0) {
      displayMessage("请选择批次记录", false);
      return;
    }
    var containers = selectData.map(function (item) {
      return {
        containerid: item.CONTAINERID,
        workflowid: item.WORKFLOWID,
        apsType: apstype
      }
    });
    //console.log(containers);
    var postData = {
      "action": "apsLmCalculateExport",
      "containers": JSON.stringify(containers)
    }
    $.messager.progress({ text: '', msg: '处理中...' });

    var xhr = new XMLHttpRequest();
    //设置响应类型为blob类型
    xhr.responseType = "blob";
    xhr.open("post", page.ajaxUrl, true); //+ "?action=apsLmCalculateExport&containers=" + JSON.stringify(containers)

    /* post 此种传参无效
    xhr.setRequestHeader('Content-Type', 'application/json');
    xhr.send(JSON.stringify(postData));
    */
    // post 这种传参有效
    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    xhr.send("action=apsLmCalculateExport&containers=" + JSON.stringify(containers) + "&ids=");


    xhr.onreadystatechange = function () {
      $.messager.progress('close');
      if (xhr.readyState == 4) {
        if (xhr.status == 200) {
          if (xhr.getResponseHeader("fileDownload") == "1") {
            var a = window.document.createElement('a');
            a.href = window.URL.createObjectURL(new Blob([this.response]));
            a.download = decodeURI(xhr.getResponseHeader("content-disposition").split('filename=')[1]);
            document.body.appendChild(a)
            a.click();
            document.body.removeChild(a)
          } else {
            var reader = new FileReader();
            reader.readAsText(this.response, 'utf-8');
            reader.onload = function (e) {
              var result = JSON.parse(reader.result);
              displayMessage(result.Message, false);
            }
          }

        }
      }
    };
    return;

  },
  //结果导出
  apsContainerScheduledTaskLogsExport: function () {
    var strPoolId = $("#PoolID").combobox('getValue');
    if (strPoolId == "") {
      displayMessage("没有排产池", false);
      return;
    }
    var param = "action=apsScheduledTaskLogsExport&containerName=" + $("#txtContainer").textbox('getValue') + "&mfgorderName=" + $("#txtMfgorderName").textbox('getValue') + "&productName=" + $("#txtProduct").textbox('getValue') +
      "&factoryId=" + $("#factoryID").combobox('getValue') + "&poolId=" + $("#PoolID").combobox('getValue') + "&orderBStartDate=" + $("#txtOrderBStartDate").datebox('getValue') + "&orderEStartDate=" + $("#txtOrderEStartDate").datebox('getValue') +
      "&orderBEndDate=" + $("#txtOrderBEndDate").datebox('getValue') + "&orderEEndDate=" + $("#txtOrderEEndDate").datebox('getValue') + "&realBStartDate2=" + $("#txtRealSStartDate2").datebox('getValue') +
      "&realEStartDate2=" + $("#txtRealEStartDate2").datebox('getValue') + "&workflowStepName=" + $("#txtStepName").textbox('getValue') + "&isPrepare=" + $("#ddlIsPrepare").combobox('getValue') + "&isAps=" + $('#IsAps').combobox('getValue') +
      "&pageSize=" + page.pageSize + "&pageNumber=" + page.pageNumber
    if (!isNullOrWhiteSpaceStr($("#txtOrderBStartDate").datebox('getValue')) && !isNullOrWhiteSpaceStr($("#txtOrderEStartDate").datebox('getValue'))) {
      if (dayjs($("#txtOrderEStartDate").datebox('getValue')) < dayjs($("#txtOrderBStartDate").datebox('getValue'))) {
        displayMessage("开始时间不能大于结束时间", false);
        return;
      }
    }
    if (!isNullOrWhiteSpaceStr($("#txtOrderBEndDate").datebox('getValue')) && !isNullOrWhiteSpaceStr($("#txtOrderEEndDate").datebox('getValue'))) {
      if (dayjs($("#txtOrderEEndDate").datebox('getValue')) < dayjs($("#txtOrderBEndDate").datebox('getValue'))) {
        displayMessage("开始时间不能大于结束时间", false);
        return;
      }
    }

    $.messager.progress({ text: '', msg: '处理中...' });

    var xhr = new XMLHttpRequest();
    //设置响应类型为blob类型
    xhr.responseType = "blob";
    xhr.open("post", page.ajaxUrl, true); //+ "?action=apsLmCalculateExport&containers=" + JSON.stringify(containers)

    /* post 此种传参无效
    xhr.setRequestHeader('Content-Type', 'application/json');
    xhr.send(JSON.stringify(postData));
    */
    // post 这种传参有效
    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    xhr.send(param);


    xhr.onreadystatechange = function () {
      $.messager.progress('close');
      if (xhr.readyState == 4) {
        if (xhr.status == 200) {
          if (xhr.getResponseHeader("fileDownload") == "1") {
            var a = window.document.createElement('a');
            a.href = window.URL.createObjectURL(new Blob([this.response]));
            a.download = decodeURI(xhr.getResponseHeader("content-disposition").split('filename=')[1]);
            document.body.appendChild(a)
            a.click();
            document.body.removeChild(a)
          } else {
            var reader = new FileReader();
            reader.readAsText(this.response, 'utf-8');
            reader.onload = function (e) {
              var result = JSON.parse(reader.result);
              displayMessage(result.Message, false);
            }
          }

        }
      }
    };
    return;

  },
  //超期分析
  overDueAnalysis: function (data) {
    clearMessage();
    var url = "ApsLMOverDueAnalysisPage.html?v=" + new Date().getTime();
    url += "&parentDiv=dgAnalysis";

    var _data = JSON.parse(data);
    if (!(_data.isOverdue == "1" || _data.isOverdue == "2")) {
      displayMessage("此策略不超期，请选择超期的策略分析！", false);
      return;
    }

    var popupData = [];

    var checkedCon = $("#gdApsPool").datagrid('getChecked').find(item => {
      return item.CONTAINERID == _data.CONTAINERID;
    });
    popupData.push({
      MFGORDERNAME: checkedCon.MFGORDERNAME,
      CONTAINERNAME: checkedCon.CONTAINERNAME,
      PRODUCTDESC: checkedCon.PRODUCTDESC,
      QTY: checkedCon.QTY,
      WORKFLOWINFO: checkedCon.WORKFLOWINFO,
      CONTAINERTYPE: checkedCon.CONTAINERTYPE,
      APSTYPE: _data.APSTYPE,
      MFGSTARTDATE: checkedCon.MFGSTARTDATE,
      MFGENDDDATE: checkedCon.MFGENDDDATE,
      ISSUBCON: checkedCon.ISSUBCON,
      containerid: checkedCon.CONTAINERID,
      workflowid: checkedCon.WORKFLOWID,
      STARTTIME: isNullOrWhiteSpaceStr(checkedCon.REALSTARTDATE2) ? checkedCon.REALSTARTDATE : checkedCon.REALSTARTDATE2,
      ENDTIME: checkedCon.MFGENDDDATE,
      TOGETHERFLAG: checkedCon.TOGETHERFLAG,
      DJDKSPECIAL: 2//单件单卡特殊处理，1：所有时间乘以大批数量,2：加工时间乘以大批数量 
    });

    $('#dgAnalysis').dialog({
      title: '超期分析建议',
      fit: false,
      width: 1000,
      height: 400,
      closed: false,
      cache: false,
      modal: true,
      content: '<iframe src="' + url + '" width="100%" height="99%" frameborder="0" scrolling="auto"></iframe>',
      popupData: popupData, //弹出页面的传参
      returnData: null,
      onClose: function () {

      }
    });
  },
  //查看甘特图
  viewGanttAndSave: function (data, isCompare) {
    var d = JSON.parse(data);
    var param = [];

    if (isCompare) {//是否是策略对比
      var allData = $("#gdContainerAps").datagrid('getData').rows;

      var containerAps = allData.filter(function (item) {
        return (item.CONTAINERID == d.CONTAINERID && item.WORKFLOWID == d.WORKFLOWID);
      });
      param.push({
        containerID: d.CONTAINERID,
        apsPlanInfoIDs: ''
      });
      containerAps.forEach(function (item) {
        param[0].apsPlanInfoIDs += item.APSPLANINFOID + ",";
      });
    } else {
      param.push({
        containerID: d.CONTAINERID,
        apsPlanInfoIDs: d.APSPLANINFOID
      });
    }

    var url = "ApsLimitedCapacityViewPage.html?v=" + new Date().getTime();
    url += "&parentDiv=dg" + "&isCompare=" + isCompare;
    $('#dg').dialog({
      title: '批次工序计划甘特图-有限产能',
      fit: true,
      top: 10,
      closed: false,
      cache: false,
      modal: true,
      content: '<iframe src="' + url + '" width="100%" height="99%" frameborder="0" scrolling="auto"></iframe>',
      popupData: param, //弹出页面的传参
      returnData: null,
      onClose: function () {
        page.searchContainerAps();
      }
    });
  },
  //查询
  searchData: function () {
    var gridID = "#gdApsPool";
    var param = {
      action: "searchData",
      pageSize: page.pageSize,
      pageNumber: page.pageNumber,
      containerName: $("#txtContainer").textbox('getValue'),
      mfgorderName: $("#txtMfgorderName").textbox('getValue'),
      productName: $("#txtProduct").textbox('getValue'),
      factoryId: $("#factoryID").combobox('getValue'),
      poolId: $("#PoolID").combobox('getValue'),//排产池yuxj20230218
      orderBStartDate: $("#txtOrderBStartDate").datebox('getValue'),
      orderEStartDate: $("#txtOrderEStartDate").datebox('getValue'),
      orderBEndDate: $("#txtOrderBEndDate").datebox('getValue'),
      orderEEndDate: $("#txtOrderEEndDate").datebox('getValue'),
      realBStartDate2: $("#txtRealSStartDate2").datebox('getValue'),//手动指定日期范围           
      realEStartDate2: $("#txtRealEStartDate2").datebox('getValue'),
      workflowStepName: $("#txtStepName").textbox('getValue'),
      isPrepare: $("#ddlIsPrepare").combobox('getValue'),
      isAps: $('#IsAps').combobox('getValue'),
      workcenterid: $("#workcenterid").textbox('getValue'),
      teamid: $("#teamid").textbox('getValue')
    };
    if (!isNullOrWhiteSpaceStr(param.orderBStartDate) && !isNullOrWhiteSpaceStr(param.orderEStartDate)) {
      if (dayjs(param.orderEStartDate) < dayjs(param.orderBStartDate)) {
        displayMessage("开始时间不能大于结束时间", false);
        return;
      }
    }
    if (!isNullOrWhiteSpaceStr(param.orderBEndDate) && !isNullOrWhiteSpaceStr(param.orderEEndDate)) {
      if (dayjs(param.orderEEndDate) < dayjs(param.orderBEndDate)) {
        displayMessage("开始时间不能大于结束时间", false);
        return;
      }
    }
    $.ajax({
      type: "Post",
      url: page.ajaxUrl,
      data: param,
      cashe: false,
      async: true,
      beforeSend: function () {
        $(gridID).datagrid('loading');
        $(this).attr("disabled", "disabled"); //禁用按钮
      },
      success: function (data) {
        //console.log(data);
        $(gridID).datagrid('loaded');
        $(this).removeAttr("disabled"); //恢复按钮
        var result = JSON.parse(data);
        if (result.Result) {
          //给分页对象赋值
          page.pagetotal = result.RowCount;
          $(gridID).datagrid('loadData', { total: result.RowCount, rows: result.DBTable });
        } else {
          displayMessage(result.Message, false);
        }
      },
      error: function (XMLHttpRequest, textStatus, errorThrown) {
        $(gridID).datagrid('loaded');
        $(this).removeAttr("disabled"); //恢复按钮
        alert(XMLHttpRequest.responseText);
      }
    });
  },
  //搜索批次排产信息
  searchContainerAps: function () {
    var rowDatas = $("#gdApsPool").datagrid("getChecked");
    if (rowDatas.length == 0) {
      return;
    }
    var containerPara = [];
    rowDatas.forEach(
      function (item) {
        containerPara.push({
          containerId: item.CONTAINERID,
          workflowId: item.WORKFLOWID
        });
      }
    );

    var param = {
      action: "getContainerLMAps",
      containers: JSON.stringify(containerPara)
    };

    $.ajax({
      type: "Post",
      url: page.ajaxUrl,
      data: param,
      cashe: false,
      async: true,
      beforeSend: function () {
        $('#gdContainerAps').datagrid('loading');
      },
      success: function (data) {
        //console.log(data);
        $('#gdContainerAps').datagrid('loaded');

        var result = JSON.parse(data);
        if (result.Result) {
          var dt = result.DBTable;
          //console.log(dt);
          $("#gdContainerAps").datagrid('loadData', { total: dt.length, rows: dt });

        } else {
          displayMessage(result.Message, false);
        }
      },
      error: function (XMLHttpRequest, textStatus, errorThrown) {
        $('#gdContainerAps').datagrid('loaded');
        alert(XMLHttpRequest.responseText);
      }
    });
  },
  //排产计算 type:1,2,3正排，倒排，瓶颈排
  apsLmCalculate: async function () {
    $("#btnLMAps").linkbutton('disable');
    $('#gdApsPool').datagrid('acceptChanges');
    var apstype = $('#apsType :checked').val();
    if (apstype == null) {
      displayMessage2("请先选择排产策略", false, ["btnLMAps"]);
      return;
    }

    //判断查询列表中是否有值
    var pageData = $("#gdApsPool").datagrid("getRows");
    if (pageData.length == 0) {
      displayMessage2("没有需要排产的数据", false, ["btnLMAps"]);
      return;
    }

    //如有勾选时，按照勾选的记录处理  
    var selectData = $("#gdApsPool").datagrid('getChecked');
    var strPoolId = $("#PoolID").combobox('getValue');
    //没有排产池且没有勾选数据时提示
    if (strPoolId == "" && selectData.length == 0) {
      displayMessage2("请选择需要排产的数据", false, ["btnLMAps"]);
      return;
    }

    var isWholePool = 0;
    //如果有排产池，不勾选时默认为排产池全部
    if (strPoolId != "" && selectData.length == 0) {
      //更改为不允许此操作
      displayMessage2("请选择批次", false, ["btnLMAps"]);
      return;
      //做特殊处理，传入参数默认取第一页
      isWholePool = 1;
      //selectData=[];
      selectData[0] = pageData[0];
    }

    var isPost = true;//是否提交post
    if (apstype == "1") {
      //时间提示验证
      var isV = selectData.every(function (item) {
        var _re = true; var nowDate = dayjs().format('YYYY-MM-DD')
        if (dayjs(item.REALSTARTDATE) < dayjs(nowDate)) {
          if (!dayjs(item.REALSTARTDATE2).isValid() || isNullOrWhiteSpaceStr(item.REALSTARTDATE2)) {
            _re = false;
          }
        }
        return _re;
      });
      if (!isV) {
        await new Promise((resolve, reject) => {
          $.messager.confirm({
            title: '提示',
            msg: '有批次排产开始日期已过期，是否手动指定开始日期？',
            ok: "直接排",
            cancel: "返回指定",
            fn: function (r) {
              if (!r) {
                isPost = false;
              }
              resolve();
            },
            onClose: function() {$("#btnLMAps").linkbutton('enable');}
          });
        });
      }

    }

    if (!isPost) {
      $("#btnLMAps").linkbutton('enable');
      return;
    }


    var containers = selectData.map(function (item) {
      return {
        apspoolid: item.APSPOOLID,
        ISSUBCON: item.ISSUBCON,
        containerid: item.CONTAINERID,
        containername: item.CONTAINERNAME,
        workflowid: item.WORKFLOWID,
        STARTTIME: isNullOrWhiteSpaceStr(item.REALSTARTDATE2) ? item.REALSTARTDATE : item.REALSTARTDATE2,
        ENDTIME: item.MFGENDDDATE,
        CONTAINERTYPE: item.CONTAINERTYPE,
        TOGETHERFLAG: item.TOGETHERFLAG,
        BEGINSEQUENCE: item.BEGINSEQUENCE,
        DJDKSPECIAL: 2,//单件单卡特殊处理，1：所有时间乘以大批数量,2：加工时间乘以大批数量
        WORKCENTERNAME:item.WORKCENTERNAME
      }
    });
    //console.log(selectData);
    var postData = {
      action: "apsLmCalculate",
      apstype: apstype,
      isWholePool: isWholePool,
      containers: JSON.stringify(containers)
    }

    $.ajax({
      type: "Post",
      url: page.ajaxUrl,
      data: postData,
      cashe: false,
      async: true,
      beforeSend: function () {
        $.messager.progress({ text: '', msg: '处理中...' });
      },
      success: function (data) {
        //console.log(data);
        $.messager.progress('close');
        var result = JSON.parse(data);
        if (result.Result) {
          var dt = result.DBTable;
          $("#gdContainerAps").datagrid('loadData', { total: dt.length, rows: dt });
          displayMessage("排产成功,错误信息请看排产日志", true);
        } else {
          displayMessage(result.Message, false);
        }
        $("#btnLMAps").linkbutton('enable');
      },
      error: function (XMLHttpRequest, textStatus, errorThrown) {
        $("#btnLMAps").linkbutton('enable');
        $.messager.progress('close');
        alert(XMLHttpRequest.responseText);
      }
    });

  },
  //添加排产池
  addApsPool: function () {
    var url = "ApsLMContainerSelect.html?v=" + new Date().getTime();
    url += "&parentDiv=dg";

    $('#dg').dialog({
      title: '选择批次到排产池',
      fit: true,
      top: 10,
      closed: false,
      cache: false,
      modal: true,
      content: '<iframe src="' + url + '" width="100%" height="99%" frameborder="0" scrolling="auto"></iframe>',
      returnData: null,
      popupData: '', //弹出页面的传参
      onClose: function () {
        var returnData = $("#dg").dialog('options').returnData; //返回数据
        if (returnData != null) {
          //console.log('更新父级数据');
          page.searchData();
          displayMessage("添加成功", true);
        }


      }
    });
  },
  //移除排产池
  removeApsPool: function () {
    var selectData = $('#gdApsPool').datagrid('getChecked');
    if (selectData.length == 0) {
      displayMessage("请选择数据", false);
      return;
    }
    var gridID = "#gdApsPool";
    var param = {
      action: "removeApsPool",
      containers: JSON.stringify(selectData)
    };
    $.ajax({
      type: "Post",
      url: page.ajaxUrl,
      data: param,
      cashe: false,
      async: true,
      beforeSend: function () {
        $(gridID).datagrid('loading');
        $(this).attr("disabled", "disabled"); //禁用按钮
      },
      success: function (data) {
        //console.log(data);
        $(gridID).datagrid('loaded');
        $(this).removeAttr("disabled"); //恢复按钮
        var result = JSON.parse(data);
        if (result.Result) {
          page.searchData();
          displayMessage("移出成功", true);
        } else {
          displayMessage(result.Message, false);
        }
      },
      error: function (XMLHttpRequest, textStatus, errorThrown) {
        $(gridID).datagrid('loaded');
        $(this).removeAttr("disabled"); //恢复按钮
        alert(XMLHttpRequest.responseText);
      }
    });
  },

  //计算排产池期量信息
  calcContainerApsPriority: function () {
    //判断查询列表中是否有值
    var pageData = $("#gdApsPool").datagrid("getRows");
    if (pageData.length == 0) {
      displayMessage("没有需要计算的数据", false);
      return;
    }
    //如有勾选时，按照勾选的记录处理  
    var selectData = $("#gdApsPool").datagrid('getChecked');
    var strPoolId = $("#PoolID").combobox('getValue');
    //没有排产池且没有勾选数据时提示
    if ((strPoolId == "") && (selectData.length == 0)) {
      displayMessage("请选择需要计算的数据", false);
      return;
    }
    var isWholePool = 0;
    //如果有排产池，不勾选时默认为排产池全部
    if ((strPoolId != "") && (selectData.length == 0)) {
      //做特殊处理，传入参数默认取第一页
      isWholePool = 1;
      selectData[0] = pageData[0];

    }

    var containers = selectData.map(function (item) {
      return {
        containerid: item.CONTAINERID,
        containername: item.CONTAINERNAME,
        workflowid: item.WORKFLOWID,
        //排产优先级计算字段
        apspoolid: item.APSPOOLID,
        prioritycodename: item.PRIORITYCODENAME,
        CriticalValue: item.CRITICALVALUE,
        StepDuration: item.STEPDURATION,
        ApsSequence: item.APSSEQUENCE,
        ENDTIME: item.MFGENDDDATE,
        CONTAINERTYPE: item.CONTAINERTYPE,
        TOGETHERFLAG: item.TOGETHERFLAG,
        DJDKSPECIAL: 1//单件单卡特殊处理，1：所有时间乘以大批数量,1：加工时间乘以大批数量 
      }
    });

    var gridID = "#gdApsPool";
    var param = {
      isWholePool: isWholePool,
      action: "calcContainerApsPriority",
      containers: JSON.stringify(containers)
    };

    $.ajax({
      type: "Post",
      isWholePool: isWholePool,
      url: page.ajaxUrl,
      data: param,
      cashe: false,
      async: true,
      beforeSend: function () {
        $(gridID).datagrid('loading');
        $(this).attr("disabled", "disabled"); //禁用按钮
      },
      success: function (data) {
        //console.log(data);
        $(gridID).datagrid('loaded');
        $(this).removeAttr("disabled"); //恢复按钮
        var result = JSON.parse(data);
        if (result.Result) {
          page.searchData();//重新查询 
          displayMessage("计算完成", true);
        } else {
          displayMessage(result.Message, false);
        }
      },
      error: function (XMLHttpRequest, textStatus, errorThrown) {
        $(gridID).datagrid('loaded');
        $(this).removeAttr("disabled"); //恢复按钮
        alert(XMLHttpRequest.responseText);
      }
    });
  },

  //清除方法，重要！！！
  reset: function (iscondition, isresult, isDetail) {
    clearMessage();
    if (iscondition) {
      $('#txtMfgorderName').textbox('clear');
      $('#txtProduct').textbox('clear');
      $('#txtContainer').textbox('clear');
      $('#txtOrderBStartDate').datebox('clear');
      $('#txtOrderEStartDate').datebox('clear');
      $('#txtOrderBEndDate').datebox('clear');
      $('#txtOrderEEndDate').datebox('clear');
      $('#txtStepName').textbox('clear');
      $('#workcenterid').textbox('clear');
      $('#teamid').textbox('clear');
    }
    if (isresult) {
      clearEasyuiDataGrid("gdApsPool", 1);
    }
    if (isDetail) {
      clearEasyuiDataGrid("gdContainerAps", 1);
      $('#apsType :checked').attr('checked', false);
    }
  }
  //排产结果导入组件初始化
  , apsUploader: function () {
    var uploader = WebUploader.create({
      // swf文件路径
      swf: page.rootPath + "/Content/webuploader/Uploader.swf",
      // 文件接收服务端。
      server: page.ajaxUrl,
      // 内部根据当前运行是创建，可能是input元素，也可能是flash.
      pick: '#btnLMApsImport',
      // 不压缩image, 默认如果是jpeg，文件上传前会压缩一把再上传！
      resize: false,
      formData: {
        action: "apsLmCalculateImport",
      },
      accept: {
        title: 'Excel',
        extensions: 'xlsx,xls',
        mimeTypes: 'excel/*'
      },
    });
    // 当有文件被添加进队列的时候，每次只传一个文件
    uploader.on('fileQueued', function (file) {
      if ($('#txtExcelFileId').val() != "") {
        var f = uploader.getFile($('#txtExcelFileId').val()); //找到上一次队列中的文件
        uploader.removeFile(f, true); //删除掉上一次队列中的文件
      }
      $('#txtExcelFileId').val(file.id);
      clearMessage();
      uploader.upload();
      $.messager.progress({ text: '', msg: '处理中...' });
    });
    //上传成功
    uploader.on('uploadSuccess', function (file, response) {
      clearMessage();
      var result = response;
      displayMessage(result.Message, true);
      $.messager.progress('close');
      if (result.ReturnData != null) { if (result.ReturnData.length > 0) { page.loadErrorData(result.ReturnData); } }
      var f = uploader.getFile(file.id); //找到上传的文件
      uploader.removeFile(f, true); //将其从队列中的删掉
      $('#txtExcelFileId').val("");

    });
    //上传失败
    uploader.on('uploadError', function (file) {
      displayMessage("上传失败", false);
      var f = uploader.getFile(file.id); //找到上传的文件
      uploader.removeFile(f, true); //将其从队列中的删掉
      $.messager.progress('close');
      $('#txtExcelFileId').val("");

    });
  },
  //排产结果导入，错误行列表
  loadErrorData: function (data) {
    $('#ErrorDg').dialog({
      title: '排产结果导入错误数据',
      top: 50,
      width: '800px',
      height: '400px',
      closed: false,
      cache: false,
      modal: true,
      buttons: [{
        text: '导出并关闭',
        handler: function () {
          page.apsLmErrorDataExport();
        }
      }, {
        text: '关闭',
        handler: function () { $('#ErrorDg').dialog('close'); }
      }]
    });
    $("#ErrorTable").datagrid('loadData', data);
  },
  //排产结果导入，错误行列表导出
  apsLmErrorDataExport: function () {
    var ids = [];
    var rows = $("#ErrorTable").datagrid('getRows');
    $.each(rows, function (index, item) {
      ids.push(item.apsplandetailid);
    });
    $.messager.progress({ text: '', msg: '处理中...' });

    var xhr = new XMLHttpRequest();
    //设置响应类型为blob类型
    xhr.responseType = "blob";
    xhr.open("post", page.ajaxUrl, true);
    // post 这种传参有效
    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    xhr.send("action=apsLmCalculateExport&ids=" + ids.join(',') + "&containers=" + JSON.stringify([]));


    xhr.onreadystatechange = function () {
      $.messager.progress('close');
      $('#ErrorDg').dialog('close');
      if (xhr.readyState == 4) {
        if (xhr.status == 200) {
          if (xhr.getResponseHeader("fileDownload") == "1") {
            var a = window.document.createElement('a');
            a.href = window.URL.createObjectURL(new Blob([this.response]));
            a.download = decodeURI(xhr.getResponseHeader("content-disposition").split('filename=')[1]);
            document.body.appendChild(a)
            a.click();
            document.body.removeChild(a)
          } else {
            var reader = new FileReader();
            reader.readAsText(this.response, 'utf-8');
            reader.onload = function (e) {
              var result = JSON.parse(reader.result);
              displayMessage(result.Message, false);
            }
          }

        }
      }
    };
  },
  //删除排产结果
  deleApsPlanInfo: function (aspPlanInfoID) {
    $.messager.confirm("删除确认", "是否删除该排产数据？", function (r) {
      if (r) {
        $.ajax({
          type: "Post",
          url: page.ajaxUrl,
          data: { action: "DeleteApsPlanInfo", aspPlanInfoID: aspPlanInfoID },
          cashe: false,
          async: true,
          beforeSend: function () {
            $.messager.progress({ text: '', msg: '处理中...' });
          },
          success: function (data) {
            $.messager.progress('close');
            var result = JSON.parse(data);
            if (result.Result) {
              page.searchContainerAps();
            }
            displayMessage(result.Message, result.Result);
          },
          error: function (XMLHttpRequest, textStatus, errorThrown) {
            $.messager.progress('close');
            alert(XMLHttpRequest.responseText);
          }
        });
      }
    });
  }
};
//排产顺序号导入
var apsSeq = {
  //绑定事件
  bind: function () {
    $("#SeqImportTable").datagrid({
      columns: [[
        { field: '批次', title: '批次', width: 200 },
        { field: '排产顺序号', title: '排产顺序号', width: 80 },
        {
          field: 'ResultMessage', title: '导入结果', width: 300, formatter: function (value, row, index) {
            if (row.IsResult) {
              return "<span color='blue'>" + value + "</span>";
            } else {
              return "<span color='red'>" + value + "</span>";
            }
          }
        }
      ]],
    });
    apsSeq.uploader();
  },
  //导入组件初始化
  uploader: function () {
    var uploaderSeq = WebUploader.create({
      // swf文件路径
      swf: page.rootPath + "/Content/webuploader/Uploader.swf",
      // 文件接收服务端。
      server: page.ajaxUrl,
      // 内部根据当前运行是创建，可能是input元素，也可能是flash.
      pick: '#btnApsSeqImport',
      // 不压缩image, 默认如果是jpeg，文件上传前会压缩一把再上传！
      resize: false,
      formData: {
        action: "ImportApsSequence",
      },
      accept: {
        title: 'Excel',
        extensions: 'xlsx,xls',
        mimeTypes: 'excel/*'
      },
    });
    // 当有文件被添加进队列的时候，每次只传一个文件
    uploaderSeq.on('fileQueued', function (file) {
      clearMessage();
      uploaderSeq.upload();
      $.messager.progress({ text: '', msg: '处理中...' });
    });
    //上传成功
    uploaderSeq.on('uploadSuccess', function (file, response) {
      clearMessage();
      var result = response;
      $.messager.progress('close');
      if (result.Result) {
        apsSeq.loadResultData(result.DBTable);
      }
      displayMessage(result.Message, result.Result);
      var f = uploaderSeq.getFile(file.id); //找到上传的文件
      uploaderSeq.removeFile(f, true); //将其从队列中的删掉

    });
    //上传失败
    uploaderSeq.on('uploadError', function (file) {
      displayMessage("上传失败", false);
      var f = uploaderSeq.getFile(file.id); //找到上传的文件
      uploaderSeq.removeFile(f, true); //将其从队列中的删掉
      $.messager.progress('close');
    });
  },
  //导入结果列表
  loadResultData: function (data) {
    $('#dgSeqImport').dialog({
      title: '排产顺序号导入结果',
      top: 50,
      width: '700px',
      height: '500px',
      closed: false,
      cache: false,
      modal: true,
      buttons: [{
        text: '关闭',
        handler: function () { $('#dgSeqImport').dialog('close'); }
      }]
    });
    $("#SeqImportTable").datagrid('loadData', data);
  }
};
$(function () {
  page.init();
  //$.messager.progress({ text: '', msg: '处理中...' });
});